import React, { useState } from 'react'
import { useDispatch } from 'react-redux'
import { login } from '@/store/actions/login'
import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import styles from './index.module.scss'
import logo from '../../assets/logo.png'
import { useHistory } from 'react-router-dom/cjs/react-router-dom.min'

// 1. 搭建登录页面结构
// 2. 登录表单校验
// 3. 登录逻辑
// 4. 封装处理 token、axios 的工具函数
// 5. 登录访问控制

const Login = props => {
  const history = useHistory()
  const dispatch = useDispatch()
  // 为加载状态定义状态
  const [loading, setLoading] = useState(false)

  const onFinish = async values => {
    setLoading(true)
    try {
      // values会是一个对象，键名就是表单项的name，键值就是表单元素的内容
      // 发送请求，进行登录
      // dispatch(action) action包括两个属性，type：动作类型  data：数据
      await dispatch(login(values))
      // await login(values)()
      message.success('登录成功', 1, () => {
        console.log('页面跳转')
        const state = history.location.state
        const pathname = (state && state.from) || '/home'
        history.replace(pathname)
      })
    } catch (e) {
      message.error(e.response.data.message, 1)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className={styles.root}>
      <Card className='login-container'>
        <img className='login-logo' src={logo} alt='' />
        {/* 登录表单 */}
        <Form
          validateTrigger={['onBlur']}
          onFinish={onFinish}
          autoComplete='off'
          size='large'
          initialValues={{
            agree: true,
            mobile: '13911111111',
            code: '246810'
          }}
        >
          <Form.Item
            name='mobile'
            rules={[
              { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不对' },
              { required: true, message: '请输入手机号' }
            ]}
          >
            <Input placeholder='请输入手机号' />
          </Form.Item>

          <Form.Item
            name='code'
            rules={[
              { len: 6, message: '验证码6个字符', validateTrigger: 'onBlur' },
              { required: true, message: '请输入验证码' }
            ]}
          >
            <Input placeholder='请输入验证码' />
          </Form.Item>

          <Form.Item
            name='agree'
            valuePropName='checked'
            rules={[
              {
                validator (rule, value) {
                  if (value) {
                    return Promise.resolve()
                  } else {
                    return Promise.reject(new Error('请阅读并同意协议'))
                  }
                }
              }
            ]}
          >
            <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
          </Form.Item>

          <Form.Item>
            {/* loading : 给按钮增加加载状态 */}
            <Button loading={loading} type='primary' htmlType='submit' block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
export default Login
